
const userModel = require('../../model/user');
const { backendApiUrl } = require('../../utils/config');
import { apiRequest,apiUpload } from '../../services/_utils/apiRequest';

Page({
  data: {
    user: {
      avatarUrl: '',
      username: '未登录',
      phone: '',
      role: ''
    },
    avatarPopupVisible: false,
    usernamePopupVisible: false,
    phonePopupVisible: false,
    newUsername: '',
    newPhone: '',
    newAvatar: ''
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
            active: 3
        })
    }
    const userData = userModel.getUserData();
    let phone = userData.info.phone || '';

    this.setData({
      user: {
        avatarUrl: ('https://www.cityofwine.cn:7501' + userData.info.avatarUrl) || 'https://www.cityofwine.cn:7501/assets/images/default_avatar.png',
        username: userData.info.username,
        phone: phone,
        role: userData.info.role
      }
    });
  },

  onAvatarClick() {
    const { role } = this.data.user;
    
    if (role === 'GUEST') {
      wx.switchTab({ url: '/pages/cabinet/cabinet' });
    } else {
      this.setData({ avatarPopupVisible: true });
    }
  },
 
  onChooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        this.setData({
          newAvatar: tempFilePath,
        });
      }
    });
  },

  onCancelAvatar() {
    this.setData({ avatarPopupVisible: false });
  },

  onConfirmAvatar() {
    if (this.data.newAvatar) {
      apiUpload({
        url: `${backendApiUrl}/users/me`,
        filePath: this.data.newAvatar,
        name: 'avatar'
      })
        .then((res) => {
          this.setData({
            'user.avatarUrl': res.avatarUrl,
            avatarPopupVisible: false
          });
          userModel.markUserDataDirty();
          wx.showToast({ title: '头像更新成功', icon: 'success' });
        })
        .catch((e) => {
          console.log("头像更新失败"+e);
          wx.showToast({ title: '头像更新失败', icon: 'error' });
        });
    }
    this.setData({ avatarPopupVisible: false });
  },

  onUsernameClick() {
    this.setData({ usernamePopupVisible: true, newUsername: this.data.user.username });
  },

  onUsernameInput(e) {
    this.setData({ newUsername: e.detail.value });
  },

  onCancelUsername() {
    this.setData({ usernamePopupVisible: false });
  },

  onConfirmUsername() {
    this.updateUserInfo({ username: this.data.newUsername });
    this.setData({ usernamePopupVisible: false });
  },

  onPhoneClick() {
    this.setData({ phonePopupVisible: true, newPhone: this.data.user.phone });
  },

  onPhoneInput(e) {
    this.setData({ newPhone: e.detail.value });
  },

  onConfirmPhone() {
    this.updateUserInfo({ phone: this.data.newPhone });
    this.setData({ phonePopupVisible: false });
  },

  onCancelPhone() {
    this.setData({ phonePopupVisible: false });
  },

  updateUserInfo(updateData) {
    apiRequest({
      url: `${backendApiUrl}/users/me`,
      method: 'POST',
      data: updateData,
      useToken: true
    })
      .then((res) => {
        this.setData({
          'user.username': res.username || this.data.user.username,
          'user.phone': res.phone || this.data.user.phone,
          usernamePopupVisible: false,
          phonePopupVisible: false
        });
        wx.showToast({ title: '更新成功', icon: 'success' });
      })
      .catch(() => {
        wx.showToast({ title: '更新失败', icon: 'error' });
      });
  },

  navigateToOrders() {
    wx.navigateTo({ url: '/pages/order/order-list/index' });
  },
  navigateToMembers() {
    const userData = userModel.getUserData();
    if (userData.info.role == "CABINET_OWNER")
      wx.navigateTo({ url: '/pages/usercenter/member-list/member-list' });
    else if (userData.info.role == "AREA_AGENT") {
      wx.navigateTo({ url: '/pages/usercenter/cabinetowner-list/cabinetowner-list' });
    }
    else if (userData.info.role == "ADMIN") {
      wx.showModal({
        title: '温馨提示',
        content: '柜主请管理后台VIP会员管理',
        showCancel: false,
      });
    }
    else {
      wx.showModal({
        title: '温馨提示',
        content: '您尚无权限进行VIP会员管理',
        showCancel: false,
      });
    }
      
  },
  navigateToAddresses() {
    wx.navigateTo({ url: '/pages/usercenter/address/list/index' });
  },
  navigateToApprovalList() {
    wx.navigateTo({ url: '/pages/approvals/index' });
  },
  navigateToApplyOwner() {
    wx.navigateTo({ url: '/pages/owner/apply/index' });
  },
  navigateToCabinetInfo() {
    wx.navigateTo({ url: '/pages/cabinet/info/index' });
  },
  navigateToHome() {
    wx.switchTab({ url: '/pages/home/index' });
  },
  navigateToCabinet() {
    wx.switchTab({ url: '/pages/cabinet/index' });
  }
});
